<?php

namespace App\V3\V3_1\Controllers;

use App\V3\V3_1\Models\StorageModel;
use App\V3\V3_1\Models\StorageShelfLocationModel;
use App\V3\V3_1\Models\StorageShelfModel;
use App\V3\V3_1\Services\StorageService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class StorageController extends BaseController
{
    /**
     * 列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/17 13:50
     * @return \Illuminate\Http\JsonResponse
     */
    public function storageList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'pageSize.required' => '参数`pageSize`丢失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`丢失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['keyword'] = empty($data['keyword'])?'':$data['keyword'];

        if($this->getUserId() == $this->getMainUserId()) {
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            if($this->isShareStorage()) {
                $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
            }
            else {
                $userId['a.user_id'] = ['EQ' => $this->getUserId()];
            }
        }

       $list = StorageService::storageList($userId,$data);
        
        if(!empty($list['data'])){
            foreach ($list['data'] as &$val){
               if(empty($val['nickname'])){
                   $val['nickname'] = "";                   
               } 
               if(empty($val['nickname'])){                   
                   $val['username'] = "";
               }
            }
        }
        return $this->success($list);
    }

    /**
     * 下拉
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/17 13:55
     * @return \Illuminate\Http\JsonResponse
     */
    public function storageSelect(Request $request)
    {
        $isAllocate = $request->input('is_allocate','0');//是否为调拨使用;0:否;1:是;

        if(!$isAllocate) {
            if($this->getUserId() == $this->getMainUserId()) {
                $userId['main_id'] = ['EQ' => $this->getMainUserId()];
            }
            else {
                if($this->isShareStorage()) {
                    $userId['main_id'] = ['EQ' => $this->getMainUserId()];
                }
                else {
                    $userId['user_id'] = ['EQ' => $this->getUserId()];
                }
            }
        }
        else {
            $userId['main_id'] = ['EQ' => $this->getMainUserId()];
        }

        return $this->success(
            StorageService::storageSelect(
                $userId
            )
        );
    }

    /**
     * 新建
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/17 14:16
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function add(Request $request)
    {
        if(empty($result = self::checkInfo($data = $request->all()))) {
            $data['storage_address'] = empty($data['storage_address'])?"":$data['storage_address'];
            if(empty($data['user_id'])) $data['user_id'] = 0;
            if($this->getUserTpye()) {//子账户添加仓库
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => $this->getUserId(),
                    'main_id' => $this->getMainUserId(),
                    'created_at' => time(),
                ];
            }
            else {//主账号添加仓库
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => $data['user_id'],
                    'main_id' => $this->getMainUserId(),
                    'created_at' => time(),
                ];
            }

            $checkStorage = StorageModel::where([
                'storage_name' => $arr['storage_name'],
                /* 'storage_address' => $arr['storage_address'], */
                'main_id' => $arr['main_id'],
            ])
                ->where('delete_flag', 0)
                ->first();

            if(!empty($checkStorage)) {
                return $this->fail('', '仓库`'.$arr['storage_name'].'-'.$arr['storage_address'].'`已存在');
            }

            DB::beginTransaction();

            try {
                $insertId = StorageModel::insertGetId($arr);

                $shelfId = StorageShelfModel::insertGetId([
                    'main_id' => $this->getMainUserId(),
                    'storage_id' => $insertId,
                    'shelf_type' => 1,
                    'created_at' => time(),
                    'sort' => 1
                ]);

                StorageShelfLocationModel::insert([
                    'main_id' => $this->getMainUserId(),
                    'storage_id' => $insertId,
                    'shelf_id' => $shelfId,
                    'location_type' => 1,
                    'created_at' => time()
                ]);

                $this->log('添加仓库',$arr);

                DB::commit();
                return $this->success($insertId);
            }
            catch(Exception $e) {
               DB::rollBack();
               Log::debug('创建仓库异常：'.var_export($e->getMessage(), true));
               return $this->fail('', $e->getMessage());
            }
        }
        else {
            return $result;
        }
    }

    private function checkInfo($data)
    {
        //参数验证
        $validator = Validator::make(
            $data,
            [
                'storage_name' =>'required',//仓库名
//                'storage_address' =>'required',//仓库地址
                /* 'user_id' =>'required',//仓库负责人id */
            ],
            [
                'storage_name.required' => '请填写仓库名称',
//                'storage_address.required' => '请填写仓库地址',
                /* 'user_id.required' => '请选择仓库负责人', */
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
    }

    public function edit(Request $request)
    {
        //验证
        $validator = Validator::make($data = $request->all(), [
            'id' =>'required|integer',//供应商客户表主键id
        ],
            [
                'id.required' => '参数`id`丢失',
            ]
        );
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if(empty(self::checkInfo($data = $request->all()))) {
            $data['storage_address'] = empty($data['storage_address'])?"":$data['storage_address'];
            if(empty($data['user_id'])) $data['user_id'] = 0;
            if($this->getUserTpye()) {//子账户添加仓库
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => $this->getUserId(),
                ];
            }
            else {//主账号添加仓库
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => $data['user_id'],
                ];
            }

            $checkInfo = StorageModel::where([
                'storage_name' => $data['storage_name'],
                /* 'storage_address' => $data['storage_address'], */
                'main_id' => $this->getMainUserId(),
                'delete_flag' => 0
            ])->where('id', '!=', $data['id'])->first();

            if(!empty($checkInfo)) {
                return $this->fail('', '仓库:'.$data['storage_name'].'-'.$data['storage_address'].'已存在');
            }

            $isUpdate = StorageModel::where('id', $data['id'])
                ->lockForUpdate()
                ->update($arr);

            if($isUpdate !== false) {
                $this->log('修改仓库信息', array_merge($arr, $data));
                return $this->success(array_merge($arr, $data));
            }
        }
        else {
            return $this->fail('', self::checkInfo($request->all()));
        }
    }

    /**
     * 删除指定仓库信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/17 14:37
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        //验证
        $validator = Validator::make($data = $request->all(), [
            'id' =>'required|integer',//供应商客户表主键id
        ],
            [
                'id.required' => '参数`id`丢失',
            ]
        );
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $result = StorageService::delete($data);

        if($result['code']) {
            return $this->fail('',$result['msg']);
        }
        else {
            $this->log('删除仓库',$data);
            return $this->success();
        }
    }

    /**
     * 仓库货架库位三级列表
     * 2022/9/17 10:46
     * Author: Sun Wu
     * @return \Illuminate\Http\JsonResponse
     */
    public function storageShelfLocation()
    {
        $data = [];
        if($this->getMainUserId() == $this->getUserId() || $this->isShareStorage()) {
            $data['main_id'] = $this->getMainUserId();
        }
        else {
            $data['user_id'] = $this->getUserId();
        }
        return $this->success(
            StorageService::storageShelfLocation($data)
        );
    }
}
